/*
 * Copyright (c) 2018-2024 北京华恒盛世科技有限公司
 * QUICKPOOL is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/

#include "common.h"
#include "quickpool.h"

/**
 * @brief       Initialize job resource usage structure.
 *
 * @param[out]  jobusage      #1: job resource usage
 */
void
init_job_resourceusage(struct jobResourceUsage *jobusage)
{
    memset(jobusage, 0, sizeof(struct jobResourceUsage));
    jobusage->mem = -1;
    jobusage->swap = -1;
    jobusage->utime = -1;
    jobusage->stime = -1;

    return;
} // end function init_job_resourceusage

/**
 * @brief       Copy job resource usage from one to another.
 *
 * @param[out]  to            #1: copy job resource usage to
 * @param[in]   from          #2: copy job resource usage from
 */
void
copy_job_resourceusage(struct jobResourceUsage *to, struct jobResourceUsage *from)
{
    to->mem = from->mem;
    to->swap = from->swap;
    to->utime = from->utime;
    to->stime = from->stime;

    if (0 < from->npids) {

        if (NULL != to->pidinfo) {
            FREEUP(to->pidinfo);
        }

        to->npids = from->npids;

        to->pidinfo = (struct pidInfo *)calloc(from->npids, sizeof(struct pidInfo));
        if (NULL == to->pidinfo) {
            return;
        }
        memcpy(to->pidinfo, from->pidinfo, from->npids*sizeof(struct pidInfo));
    } else if (0 < to->npids) {
        FREEUP(to->pidinfo);
        to->npids = 0;
    }

    if (0 < from->npgids) {

        if (NULL != to->pgid) {
            FREEUP(to->pgid);
        }

        to->npgids = from->npgids;

        to->pgid = (int *)calloc(from->npgids, sizeof(int));
        if (NULL == to->pgid) {
            return;
        }
        memcpy(to->pgid, from->pgid, from->npgids*sizeof(int));
    } else if (0 < to->npgids) {
        FREEUP(to->pgid);
        to->npgids = 0;
    }

    return;
} // end function copy_job_resourceusage

/**
 * @brief       duplicate job resource usage.
 *
 * @param[out]  to            #1: copy job resource usage to
 * @param[in]   from          #2: copy job resource usage from
 */
struct jobResourceUsage *
dup_job_resourceusage(unsigned int num, struct jobResourceUsage *jobusage)
{
    struct jobResourceUsage *toUsage;
    toUsage = (struct jobResourceUsage *)calloc(num, sizeof(struct jobResourceUsage));
    if (NULL == toUsage) {
        return NULL;
    }

    unsigned int i;
    for (i=0; i<num; i++) {
        copy_job_resourceusage(&(toUsage[i]), &(jobusage[i]));
    }

    return toUsage;
} // end function dup_job_resourceusage
